<?php
namespace app\commands;

use app\models\Price;
use yii\console\Controller;

class PriceController extends Controller
{
    public function actionIndex()
    {
        $url = 'http://ncpprice.haagri.gov.cn/price_new1.asp?market=&kindname=&Page=';
        $html = file_get_contents($url.'1');
        $html = iconv("gb2312","utf-8//IGNORE",$html);
        preg_match('/页次\:\d+\/\d+/',$html,$matchs);
        $page_count = (integer)str_replace('页次:1/','',$matchs[0]);
        for ($i = 1; $i <= $page_count; $i++) {
            echo $url.$i.PHP_EOL;
            $this->GetPage($url.$i);
        }
    }

    function GetPage($url)
    {
        $html = file_get_contents($url);
        preg_match('/<table[.\s\S]*?>[.\s\S]*?<\/table>/',$html,$matchs);
        $html = $matchs[0];
        $html = preg_replace("'<div[^>]*?>.*<\/div>'si","",$html);
        $html = iconv("gb2312","utf-8//IGNORE",$html);
        $result = $this->get_td_array($html);
        //var_dump($result);die;
        $count = 0;
        foreach ($result as $res) {
            $pri = new Price();
            $pri->name = $res[0];
            $pri->market = $res[1];
            $pri->price_kg = $res[2];
            $pri->price_jin = $res[2]/2;
            $date_m = date_create($res[3]);//日期格式转化
            $pri->date = date_format($date_m,'Y-m-d');
            if($pri->save()) {
                $count++;
            }
        }
        echo "爬取完成，成功数：".$count.PHP_EOL;
    }

    function get_td_array($table) {
        $table = preg_replace("'<table[^>]*?>'si","",$table);
        $table = preg_replace("'<tr[^>]*?>'si","",$table);
        $table = preg_replace("'<td[^>]*?>'si","",$table);
        $table = str_replace("</tr>","{tr}",$table);
        $table = str_replace("</td>","{td}",$table);
        //去掉 HTML 标记
        $table = preg_replace("'<[/!]*?[^<>]*?>'si","",$table);
        //去掉空白字符
        //$table = preg_replace("'([rn])[s]+'","",$table);
        $table = preg_replace("/\s+/","",$table);
        $table = str_replace(" ","",$table);
        $table = str_replace(" ","",$table);
        $table = explode('{tr}', $table);
        array_pop($table);
        foreach ($table as $key=>$tr) {
            $td = explode('{td}', $tr);
            array_pop($td);
            $td[2] = str_replace('&nbsp;元/公斤','',$td[2]);
            $td[3] = str_replace('&nbsp;','',$td[3]);
            $td_array[] = $td;
        }
        return $td_array;
    }

    /*
     * 时间格式标准化
     */
    public function actionConvert()
    {
        $pris = Price::find()->all();
        $count = 0;
        foreach ($pris as $pri) {
            $date = $pri->date;
            $date = date_create($date);
            $date = date_format($date,'Y-m-d');
            $pri->date = $date;
            $pri->save();
            $count++;
            echo $count.PHP_EOL;
        }
    }
}
